package control

import (
	"errors"
	"fmt"
	"service/app/dao"
	"service/app/dto"
	"service/app/mode"

	"github.com/casbin/casbin/v2"
)

type UserContr struct {
	BaseContr
	Dao *dao.UserDao
	Cb  *casbin.Enforcer
}

var UserC *UserContr

func NewUserContr() *UserContr {
	if UserC == nil {
		UserC = &UserContr{
			Dao: dao.NewUserDao(),
		}
	}
	return UserC
}

func (m *UserContr) InfoUserC(profile *mode.Lz_user) (*dto.IresUserInfo, error) {
	var trimInfo dto.IresUserInfo
	//test 管理员测试,auth (menu列表中)
	if profile.User == "admin" {
		// 获取所有menus列表
		menu, err := menusCont.MenuGetAll()
		if err != nil {
			return nil, err
		}
		trimInfo.Menus = menu

	} else {
		trimInfo.ConverToRes(profile)
		trimInfo.Roles = &profile.Roles
		menulist, err := m.Dao.InfoUserD(&profile.Roles)
		if err != nil {
			return nil, err
		}
		trimInfo.Menus = menulist
	}
	return &trimInfo, nil
}

func (m *UserContr) Login(userName, ip string) (*mode.Lz_user, error) {

	user, err := m.Dao.FindUserByUsername(userName, ip)
	// Iuser := m.Dao.FindUbyUserAndPw(user, password)
	if user.ID == 0 {
		err = errors.New("查询的用户不存在!")
	}
	return user, err
}

// 从校验赋值会传过来的值写入数据库
func (m *UserContr) AddUser(info *dto.AdduserDto) error {
	// 先判断用户是否存在
	exist := m.Dao.ExistUserByName(info.User)
	if exist {
		str := fmt.Sprintf("用户名：%s 已存在!", info.User)
		return errors.New(str)
	}
	// 写入成功,返回对象
	return m.Dao.AddUser(info)
}

func (m *UserContr) GetUserById(id dto.ReqUriIdDto) (mode.Lz_user, error) {
	return m.Dao.GetUserById(id)
}

func (m *UserContr) GetUserList(paginat *dto.ReqPaginat) (*[]mode.IresUserList, int64, error) {
	return m.Dao.PaginatUser(paginat)
}

func (m *UserContr) UpdataUser(user dto.UpdataUserDto) error {
	return m.Dao.UpdataUser(user)
}
func (m *UserContr) DelUser(userId dto.ReqUriIdDto) error {
	return m.Dao.DelUser(userId)

}

func (m *UserContr) UserPermC(id int) (*mode.Lz_user, error) {
	return m.Dao.UserPermD(id)
}
